package com.charon.common.websocket;

import java.io.IOException;
import java.util.ArrayList;

import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

/**
 * @ClassName：SocketHandler.java
 * @Description: WebSocket处理器
 * @Author charon [248135724@qq.com]
 * @Date: 2018年11月16日 下午8:54:31
 * @version V1.0
 */
public class SocketHandler extends TextWebSocketHandler {
	private static final ArrayList<WebSocketSession> users = new ArrayList<WebSocketSession>();;// 这个会出现性能问题，最好用Map来存储，key用userid

	/**
	 * 建立连接后触发的回调
	 */
	@Override
	public void afterConnectionEstablished(WebSocketSession session) {
		System.out.println("connect to the websocket success......当前数量:" + users.size());
		users.add(session);
		// 这块会实现自己业务，比如，当用户登录后，会把离线消息推送给用户
		// TextMessage returnMessage = new TextMessage("你将收到的离线");
		// session.sendMessage(returnMessage);
	}

	/**
	 * 收到消息时触发的回调
	 */
	@Override
	public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) {
		System.out.println("消息回调");
		message.getPayload().toString();
		TextMessage returnMessage = new TextMessage("服务器返回消息");
		try {
			session.sendMessage(returnMessage);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 传输消息出错时触发的回调
	 */
	@Override
	public void handleTransportError(WebSocketSession session, Throwable exception) {

	}

	/**
	 * 断开连接后触发的回调
	 */
	@Override
	public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) {

	}

}
